package org.pentaho.cubic.client.dialogs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import org.pentaho.cubic.client.explorer.tab.CubicTabLayoutPanel;
import org.pentaho.cubic.client.service.CubicServiceCache;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class NewAnalysisDialog extends DialogBox {

	private static NewAnalysisDialogUiBinder uiBinder = GWT
	.create(NewAnalysisDialogUiBinder.class);

	interface NewAnalysisDialogUiBinder extends
	UiBinder<Widget, NewAnalysisDialog> {
	}

	@UiField ListBox lboxSchema;
	@UiField ListBox lboxCube;
	@UiField Button btnOK;
	@UiField Button btnCancle;

	public static final String FOCUS_ON_TITLE = "title"; //$NON-NLS-1$
	private HashMap<String, ArrayList<String[]>> schemaCubeHashMap;

	public NewAnalysisDialog() {
		setWidget(uiBinder.createAndBindUi(this));
		this.setText("New Analysis View");
		this.setGlassEnabled(true);
		
		buildAnalysisView();
		lboxSchema.getElement().setId("schemaList");
		lboxSchema.setTabIndex(1);
		lboxCube.getElement().setId("cubeList");
		lboxCube.setTabIndex(2);

		lboxSchema.setFocus(true);
	}

	@UiHandler("btnOK")
	void onClickOK(ClickEvent e) {
		if (validate()) {

			String actionName = System.currentTimeMillis() + ".analysisview.xaction"; //$NON-NLS-1$
			String newAnalysisViewURL = "AnalysisViewService?component=createNewView&name=" + actionName + "&descr=" + actionName + "&actionName=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			+ actionName + "&textfield=&schema=" + getSchema() + "&cube=" + getCube() + "&solution=system&actionPath=tmp"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			if (!GWT.isScript()) {
				newAnalysisViewURL = "http://localhost:8080/pentaho/" + newAnalysisViewURL + "&userid=joe&password=password"; //$NON-NLS-1$ //$NON-NLS-2$
			}

			//CubicTabLayoutPanel.getInstance().addTab("New Analysis View", "New Analysis View", "/pentaho/" + newAnalysisViewURL);
			CubicTabLayoutPanel.getInstance().addTab("New Analysis View", "New Analysis View", "/pentaho/" + newAnalysisViewURL);
			this.hide();

			// Set it to save-enabled and fire event
			//navigatorPerspective.getContentTabPanel().getCurrentFrame().setSaveEnabled(true);
			//navigatorPerspective.fireSolutionBrowserListenerEvent(SolutionBrowserListener.EventType.OPEN, MantleTabPanel.CURRENT_SELECTED_TAB);

			// navigatorPerspective.refreshPerspective(false);
		}
	}

	@UiHandler("btnCancle")
	void onClickCancle(ClickEvent e) {
		this.hide();
	}

	/**
	 * Actual construction of the New Analysis View Dialog.
	 * 
	 * @return The container that contains all the requisite widget.
	 */
	private void buildAnalysisView() {

		lboxSchema.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				final String currentSchema = lboxSchema.getItemText(lboxSchema.getSelectedIndex());
				updateCubeListBox(currentSchema);
			}
		});

		// Get the pertinent information for the cube and the schema.
		getSchemaAndCubeInfo();

		lboxSchema.setWidth("15em"); //$NON-NLS-1$
		lboxCube.setWidth("15em"); //$NON-NLS-1$

	}
	/*
	 * We only need get methods because the set is implemented by the widget itself.
	 */

	public String getSchema() {
		return lboxSchema.getItemText(lboxSchema.getSelectedIndex());
	}

	public String getCube() {
		return lboxCube.getValue(lboxCube.getSelectedIndex());
	}

	/**
	 * Populates the schema and cube list box based on the information retrieved from the catalogs.
	 */
	private void getSchemaAndCubeInfo() {
		AsyncCallback<HashMap<String, ArrayList<String[]>>> callback = new AsyncCallback<HashMap<String, ArrayList<String[]>>>() {
			public void onFailure(Throwable caught) {
				NotificationDialog dialogBox = new NotificationDialog("Error", "Could Not Get File Properties"); //$NON-NLS-1$
				dialogBox.center();
			}

			public void onSuccess(HashMap<String, ArrayList<String[]>> result) {
				if (result != null) {
					schemaCubeHashMap = result;

					if (schemaCubeHashMap != null && schemaCubeHashMap.size() >= 1) {

						for (Entry<String, ArrayList<String[]>> entry : schemaCubeHashMap.entrySet()) {
							lboxSchema.addItem(entry.getKey());
						}

						lboxSchema.setSelectedIndex(0);
						updateCubeListBox(lboxSchema.getItemText(lboxSchema.getSelectedIndex()));
					}
				} else {
					NotificationDialog dialogBox = new NotificationDialog("Error", "No Mondrian Schemas"); //$NON-NLS-1$ //$NON-NLS-2$
					dialogBox.center();
				}
			}
		};

		CubicServiceCache.getService().getMondrianCatalogs(callback);
	}

	/**
	 * This method updates the cube list box based on the selection in the schema list box.
	 * 
	 * @param currentSchema
	 *          The schema currently selected.
	 */
	public void updateCubeListBox(String currentSchema) {
		lboxCube.clear();

		ArrayList<String[]> cubeNamesList = schemaCubeHashMap.get(currentSchema);
		int size = cubeNamesList.size();

		for (int i = 0; i < size; i++) {
			String name = cubeNamesList.get(i)[0];
			String id = cubeNamesList.get(i)[1];
			lboxCube.addItem(name, id);
		}
	}

	/**
	 * Checks the input fields for input.
	 * 
	 * @return Returns false if the expected inputs were not provided.
	 */
	public boolean validate() {
		final String schema = getSchema();
		if (schema == null || schema.length() == 0) {
			NotificationDialog dialogBox = new NotificationDialog("Error", "Select Schema"); //$NON-NLS-1$ //$NON-NLS-2$
			dialogBox.setWidth("15em"); //$NON-NLS-1$
			dialogBox.center();
			return false;
		}

		final String cube = getSchema();
		if (cube == null || cube.length() == 0) {
			NotificationDialog dialogBox = new NotificationDialog("Error", "Select Cube"); //$NON-NLS-1$ //$NON-NLS-2$
			dialogBox.setWidth("15em"); //$NON-NLS-1$
			dialogBox.center();
			return false;
		}

		return true;
	}

}
